package com.mobi.Survey.adapters;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.TextView;

import com.mobi.Survey.map.Category;
import com.mobi.Survey.map.R;

public class CustomAdapterCategoriesAddBusiness extends BaseAdapter {

	private List<Category> categories;
	private LayoutInflater mInflater;
	private Set<Long> selectedCatIds = new HashSet<Long>();

	private boolean subCategoryView;

	
	
	public Set<Long> getSelectedCategories() {
		return selectedCatIds;
	}

	public CustomAdapterCategoriesAddBusiness(Context ctx, List<Category> categories) {
		this.mInflater = LayoutInflater.from(ctx);
		this.categories = categories;
	}

	public void switchToSubCategoryView(boolean isSwitch) {
		this.subCategoryView = isSwitch;
	}

	public boolean isSubCategoryView() {
		return this.subCategoryView;
	}

	public void setData(List<Category> categories) {
		this.categories = categories;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		return categories.size();
	}

	@Override
	public Category getItem(int position) {

		return categories.get(position);
	}

	@Override
	public long getItemId(int arg0) {
		// TODO Auto-generated method stub
		return 0;
	}

	static final class ViewHolder {

		TextView catName;
		CheckBox cbSelect;

	}

	@Override
	public View getView(final int position, View convertView, ViewGroup arg2) {

		final Category category = categories.get(position);
		final ViewHolder holder;
		if (convertView == null) {

			convertView = mInflater.inflate(R.layout.select_categories_row, null);

			holder = new ViewHolder();

			holder.catName = (TextView) convertView.findViewById(R.id.catName);

			holder.cbSelect = (CheckBox) convertView.findViewById(R.id.cbSelect);

			convertView.setTag(holder);

		} else {
			holder = (ViewHolder) convertView.getTag();

		}

		if (subCategoryView) {
			holder.cbSelect.setVisibility(View.VISIBLE);

			holder.cbSelect.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View v) {

					if (holder.cbSelect.isChecked()) {
						if (selectedCatIds.size() == 3) {
							holder.cbSelect.setChecked(false);
						} else
							selectedCatIds.add(category.getId());
					} else
						selectedCatIds.remove(category.getId());

				}
			});

			if (selectedCatIds.contains(category.getId())) {
				holder.cbSelect.setChecked(true);
			} else {
				holder.cbSelect.setChecked(false);
			}
		} else if (View.VISIBLE == holder.cbSelect.getVisibility()) {
			holder.cbSelect.setVisibility(View.GONE);
		}
		holder.catName.setText(category.getName());

		return convertView;

	}
}
